package com.aind.user.service.impl;

import com.aind.common.utils.RandomChars;
import com.aind.common.utils.mail.Mail;
import com.aind.common.utils.mail.MailUtils;
import com.aind.user.dao.UserMapper;
import com.aind.user.model.User;
import com.aind.user.model.UserExample;
import com.aind.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.Session;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.List;
import java.util.Properties;

/**
 * Created by lpeng on 2017/1/20.
 */
@Service
public class UserServiceImpl implements UserService {
    private static Logger logger = Logger.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public void saveTest(){
        User u1 = new User();
        u1.setAccount("1234");
        userMapper.insertSelective(u1);
        int i = 1/0;
        User u2 = new User();
        u1.setAccount("1234");
        userMapper.insertSelective(u2);
    }

    /**
     * 保存用户
     *
     * @param user
     * @return
     */
    @Override
    public long save(User user) {
        String activationCode = RandomChars.getRanChars(10);
        user.setActivationcode(activationCode);
        user.setStatus((byte) 2);
        userMapper.insert(user);
        logger.info("insert into user, return id: [ " + user.getUserId() + " ]");
        if (null != user && StringUtils.isNotEmpty(user.getEmail())) {
            try {
                sendActivateMail(user.getEmail(), Long.toString(user.getUserId()), activationCode);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("邮件发送失败: " + e);
            }
            logger.info("邮件发送成功--收件人: 【 " + user.getEmail() + "】");
        }
        return user.getUserId();
    }

    /**
     * 校验用户名
     *
     * @param account 帐号
     * @return boolean
     */
    @Override
    public boolean checkAccount(String account) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andAccountEqualTo(account);
        List<User> users = userMapper.selectByExample(userExample);
        return users.size() > 0 ? false : true;
    }

    /**
     * 激活用户
     *
     * @param userId         用户id
     * @param activationCode 激活码
     * @return
     */
    @Override
    public boolean activateUser(Long userId, String activationCode) {
        User user = new User();
        user.setStatus((byte) 1);
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUserIdEqualTo(userId).andActivationcodeEqualTo(activationCode);
        int i = userMapper.updateByExampleSelective(user, userExample);
        return i > 0 ? true : false;
    }

    /**
     * 发送邮件
     *
     * @param recipients
     * @param activationCode
     */
    private void sendActivateMail(String recipients, String userId, String activationCode) throws IOException, MessagingException {
        Properties properties = new Properties();
        properties.load(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("activationCode_mail.properties"), "UTF-8"));
        String account = properties.getProperty("account");//邮箱帐号
        String password = properties.getProperty("password");//邮箱密码
        String host = properties.getProperty("host");//服务器
        String from = properties.getProperty("from");//发件人
        String subject = properties.getProperty("subject");//主题
        String content = MessageFormat.format(properties.getProperty("content"), activationCode, userId);//邮件内容
        Session session = MailUtils.createSession(host, account, password);//会话
        Mail mail = new Mail(from, recipients, subject, content);//邮件
        MailUtils.send(session, mail);//发送邮件
    }

    /**
     * 通过帐号和密码查询用户
     *
     * @param account  帐号
     * @param password 密码
     * @return
     */
    @Override
    public User getUserByAccountAndPswd(String account, String password) {
        User user = null;
        UserExample userExample = new UserExample();
        userExample.createCriteria().andAccountEqualTo(account).andPasswordEqualTo(password);
        List<User> users = userMapper.selectByExample(userExample);
        if (!users.isEmpty()) {
            user = users.get(0);
        }
        return user;
    }

    /**
     * 通过用户id查找用户
     *
     * @param userId
     * @return
     */
    @Override
    public User getUserByUserId(Long userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    /**
     * 更新用户密码
     *
     * @param userId
     * @param newpassword
     * @return
     */
    @Override
    public boolean modifyUserPswdById(Long userId, String newpassword) {
        User user = new User();
        user.setUserId(userId);
        user.setPassword(newpassword);
        int i = userMapper.updateByPrimaryKeySelective(user);
        return i > 0 ? true : false;
    }

    @Override
    public void getPager(User user) {
        userMapper.getPager(user);
    }
}
